﻿using System;
using System.ComponentModel;

namespace Micro.Extensions.Utilities
{
    public static class EnumExtensions
    {
        /// <summary>
        /// 获取枚举描述
        /// </summary>
        /// <param name="enumeration"></param>
        /// <returns></returns>
        public static string ToDescription(this Enum enumeration)
        {
            var enumType = enumeration.GetType();
            string name = Enum.GetName(enumType, enumeration);
            if (name == null) return null;

            var fieldInfo = enumType.GetField(name);
            if (fieldInfo == null) return null;

            var attr = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute), false) as DescriptionAttribute;
            return attr?.Description;
        }

        /// <summary>
        /// 枚举转换为Int值
        /// </summary>
        /// <param name="enumeration"></param>
        /// <returns></returns>
        public static int ToInt(this Enum enumeration)
        {
            return Convert.ToInt32(enumeration);
        }

        /// <summary>
        /// 枚举值强转为枚举，转换失败抛出exception
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="val"></param>
        /// <returns></returns>
        public static T ToEnum<T>(this string val)
        {
            return (T)Enum.Parse(typeof(T), val);
        }
    }
}
